<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>板块趋势分析</title>
    <script src="/js/ll.js"></script>
    <link href="/css/font.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        accent: '#0ea5e9',
                        neutral: '#f1f5f9',
                        'neutral-dark': '#334155',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .table-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .table-fixed-layout {
                table-layout: fixed; /* 固定表格布局，确保表头宽度稳定 */
                width: 100%;
            }
            .table-fixed-layout th,
            .table-fixed-layout td {
                border: 1px solid #ddd;  /* 细线边框 */
                padding: 8px;
                white-space: nowrap; /* 防止内容换行导致表头高度变化 */
            }

            .hover-scale {
                transition: all 0.2s ease-in-out;
            }
            .hover-scale:hover {
                box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
            }
            .sortable-header {
                cursor: pointer;
                user-select: none;
                transition: all 0.2s ease;
            }
            .sortable-header:hover {
                background-color: #f3f4f6;
                transform: none;
            }
            .sort-icon {
                margin-left: 4px;
                opacity: 0.5;
            }
            .sort-icon.active {
                opacity: 1;
                color: #3b82f6;
            }
            /* 滚动置顶相关样式 */
            .sticky-header {
                position: sticky;
                top: 0;
                z-index: 50; /* 最高层级，确保不被覆盖 */
            }
            .sticky-search {
                position: sticky;
                top: 60px; /* 导航栏高度约60px，紧跟其下方 */
                z-index: 40;
                background: white; /* 白色背景覆盖下方内容 */
                padding-top: 16px; /* 补充间距 */
            }
            /* 表格头部行整体置顶 */
            .sticky-table-header {
                position: sticky;
                top: 240px; /* 导航栏(60px) + 搜索区(约180px)，合计240px */
                z-index: 30;
            }

            .sticky-table-header th {
                background: #f9fafb; /* 表头背景色 */
            }

            .sticky-container {
                position: sticky;
                top: 0;
                z-index: 50;
                background-color: #f9fafb; /* 与页面背景色一致 */
            }

            .sticky-header {
                position: sticky;
                top: 0;
                z-index: 50;
            }

            .sticky-content {
                position: sticky;
                top: 60px; /* 导航栏高度 */
                z-index: 49;
            }

            /* 解决内容被遮挡问题 */
            .overflow-x-auto {
                position: relative;
                z-index: 10;
                margin-top: -24px; /* 抵消mb-6的间距 */
                padding-top: 24px;
            }

            /* 紧凑按钮样式 */
            .compact-btn {
                @apply px-3 py-2 rounded-md transition-colors text-sm flex items-center;
            }

            /* 表格统计信息样式 */
            .table-stats {
                @apply bg-gray-50 px-4 py-2 text-sm text-gray-600 border border-t-0 border-gray-200 rounded-b-lg;
            }

            /* 数据更新时间样式 */
            .update-time {
                @apply text-lg text-gray-500 italic;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<div class="sticky-container">
    <!-- 导航头部 - 滚动置顶 -->
    <header class="bg-white shadow-sm sticky-header">
        <!--        <div class="container mx-auto px-4 py-3 flex flex-wrap items-center justify-between gap-2">-->
        <!--    <header class="bg-primary text-white shadow-md w-full sticky top-0 z-50">-->
        <div class="flex justify-between items-center px-4 py-1">
            <!-- 左侧标题区域 -->
            <div class="flex items-center w-full justify-start px-0 py-0 space-x-4">
                <i class="fa fa-line-chart text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">板块趋势分析</h1>
                <!-- 新增：数据更新时间显示 -->
                <div class="text-lg update-time ml-4"  style="color: red">
                    最后更新: <span id="lastUpdateTime">-</span>
                </div>
                <h2 class="text-xl md:text-2xl font-bold" style="color: red">{大盘->板块->个股||主力->热度->分时}概念:前50,个股:前500</h2>

                <ul class="flex space-x-4 sm:space-x-6">
                    <li><a href="/" class="text-primary font-medium hover:text-primary/80 transition-colors">首页</a></li>
                    <li><a href="/analysis" class="text-gray-600 hover:text-primary transition-colors">数据分析</a></li>
                    <li><a href="/limitup/search" class="text-gray-600 hover:text-primary transition-colors">ZT分析</a></li>
                    <li><a href="/stocksflow" class="text-gray-600 hover:text-primary transition-colors">个股资金</a></li>
                    <li><a href="/gainian" class="text-gray-600 hover:text-primary transition-colors">概念资金</a></li>
                </ul>
                <!-- 查询/刷新按钮 -->
                <div class="flex items-end">
                    <button id="searchBtn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-all duration-300 flex items-center">
                        <i class="fa fa-search mr-2"></i>查询/刷新
                    </button>
                </div>
            </div>
        </div>

        <div class="flex justify-between items-center px-4 py-1">
            <!-- 右侧按钮和导航链接区域 - 分为上下两部分避免换行问题 -->
            <div class="w-full md:w-auto flex flex-col md:flex-row md:items-center gap-2">
                <!-- 按钮组 -->
                <div class="flex flex-wrap items-center gap-2">
                    <button id="delSelectStock" class="text-white compact-btn bg-green-600 hover:bg-green-700" onclick="removeupdateFocusGainian()">
                        <span>取消关注</span>
                    </button>
                    <button id="addSelectStock" class="text-white compact-btn bg-secondary hover:bg-secondary/90" onclick="addupdateFocusGainian()">
                        <span>关注选择</span>
                    </button>
                    <button id="SelectStock" class="text-white compact-btn bg-green-600 hover:bg-green-700" onclick="getSelectedStockCodesJQ()">
                        <span>复制选择</span>
                    </button>
                    <button id="SelectStockSearch" class="text-white compact-btn bg-secondary hover:bg-secondary/90" onclick="jumpToEastMoneySearch()">
                        <span>查询资讯</span>
                    </button>
                    <button id="getGainian" class="text-white compact-btn bg-green-600 hover:bg-green-700" onclick="openSelectedGainianCodesJQ()">
                        <span>查看选择</span>
                    </button>
                    <!-- 新增重置过滤按钮 -->
                    <button id="resetFilters" class="text-white compact-btn bg-gray-600 hover:bg-gray-700" onclick="resetAllFilters()">
                        <i class="fa fa-refresh mr-1"></i>重置
                    </button>
                </div>

                <span class="hidden md:inline">||</span>
                <div class="flex items-center text-lg">
                    总数:<span id="totalCount" class=" text-gray-900">-</span> &nbsp;
                    上涨:<span id="upCount" class=" text-red-500">-</span>&nbsp;
                    下跌:<span id="downCount" class=" text-green-500">-</span>&nbsp;
                    平盘:<span id="pinCount" class=" text-gray-700">-</span>&nbsp;
                    涨停:<span id="limitUpCount" class=" text-red-600">-</span>&nbsp;
                </div>

            </div>

        </div>

        <div class="flex items-center text-lg">
            关注:<span id="flowGainian" class="font-medium text-red-600">-</span>
        </div>

        <div class="flex justify-between items-center px-4 py-1">
            <!--        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">-->
            <!-- 搜索区域与按钮整合 - 增加了更多过滤条件 -->
            <div class="flex-1 flex flex-col md:flex-row gap-4 items-start md:items-center w-full flex-wrap">
                <!-- 名称模糊查询 -->
                <div class="flex-1 min-w-[200px]">
                    <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                    <i class="fa fa-search text-gray-400"></i>
                </span>
                        <input
                                type="text"
                                id="nameSearch"
                                placeholder="输入概念名称关键词搜索...=关注"
                                class="block w-full pl-10 pr-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                        >
                    </div>
                </div>

                <!-- 时间范围查询 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="flex gap-2">
                        <input
                                type="date"
                                id="startDate"
                                class="flex-1 px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                        >
                    </div>
                </div>

                <!-- 涨幅过滤 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="relative">
                        <select id="changePercentFilter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="">所有涨幅</option>
                            <option value="0.01-2">0-2%</option>
                            <option value="2-5">2-5%</option>
                            <option value="5-7">5-7%</option>
                            <option value="7-10">7-10%</option>
                            <option value="10+">10%以上</option>
                            <option value="-2-0">-2-0%</option>
                            <option value="-5-2">-5--2%</option>
                            <option value="-7-5">-7--5%</option>
                            <option value="-10-7">-10--7%</option>
                            <option value="-10-">低于-10%</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                    </span>
                    </div>
                </div>

                <!-- 1天资金过滤 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="relative">
                        <select id="day1Filter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="">所有1天资金</option>
                            <option value="0.01-50">0-50亿</option>
                            <option value="50-100">50-100亿</option>
                            <option value="100-500">100-500亿</option>
                            <option value="500+">500亿以上</option>
                            <option value="-50-0">-50-0亿</option>
                            <option value="-100-50">-100--50亿</option>
                            <option value="-500-100">-500--100亿</option>
                            <option value="-500-">低于-500亿</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                    </span>
                    </div>
                </div>

                <!-- 上涨率过滤 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="relative">
                        <select id="upRatioFilter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="">最新所有热度</option>
                            <option value="1-50">0-50</option>
                            <option value="50-150">50-150</option>
                            <option value="150-400">150-400</option>
                            <option value="400-2000">大于400</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                    </span>
                    </div>
                </div>

                <!-- 涨停率过滤 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="relative">
                        <select id="limitUpRatioFilter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="">所有涨停率</option>
                            <option value="0.01-5">0-5%</option>
                            <option value="5-10">5-10%</option>
                            <option value="10-20">10-20%</option>
                            <option value="20+">20%以上</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                    </span>
                    </div>
                </div>

                <!-- 趋势过滤 -->
                <div class="flex-1 min-w-[150px]">
                    <div class="relative">
                        <select id="trendFilter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="all">所有趋势</option>
                            <option value="上升">上升</option>
                            <option value="下降">下降</option>
                            <option value="反转">反转</option>
                            <option value="平稳">平稳</option>
                            <option value="前50">前50</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                        <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                    </span>
                    </div>
                </div>

                <!-- 成员数过滤 -->
                <div class="flex-1 min-w-[180px]">
                    <div class="relative">
                        <select id="memberCountFilter" class="block w-full px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary appearance-none bg-white">
                            <option value="" selected>所有成员数</option>
                            <option value="0-0">无成员</option>
                            <option value="1-10000">有成员</option>
                            <option value="1-100">1-100</option>
                            <option value="101-300">101-300</option>
                            <option value="301-500">301-500</option>
                            <option value="501-1000">501-1000</option>
                            <option value="1001+">1001以上</option>
                        </select>
                        <span class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                            <i class="fa fa-chevron-down text-gray-400 text-xs"></i>
                        </span>
                    </div>
                </div>


            </div>
        </div>

    </header>


    <div class="overflow-x-auto">
        <table class="w-full divide-y divide-gray-200 table-fixed-layout">
            <thead class="bg-gray-50">
            <tr>
                <th class="px-2 py-2 text-xs font-medium text-gray-500 w-16" style="width: 28px;" >
                    <input type="checkbox" id="select-all" class="select-all">
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider sortable-header" data-sort="createTime" style="width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                    日期
                    <i class="fa fa-sort sort-icon"></i>
                </th>
                <th scope="col"  class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider sortable-header" data-sort="marketValue" style="width: 90px;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                    市值(亿)
                    <i class="fa fa-sort sort-icon"></i>
                </th>
                <th scope="col"  class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider sortable-header" data-sort="changePercent" style="width: 65px;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                    涨幅
                    <i class="fa fa-sort sort-icon"></i>
                </th>

                <!-- 概念名称列：固定宽度200px，内容超长省略，添加排序功能 -->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider sortable-header" data-sort="gainianName" style="width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                    概念名称
                    <i class="fa fa-sort sort-icon"></i>
                </th>
                <!-- 概念名称列：固定宽度200px，内容超长省略，添加排序功能 -->

                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 60px;" data-sort="day1">
                    1天
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day2">-->
<!--                    2天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day2now">
                    2天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day3">-->
<!--                    3天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day3now">
                    3天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day4">-->
<!--                    4天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day4now">
                    4天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day5">-->
<!--                    5天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day5now">
                    5天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day6">-->
<!--                    6天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day6now">
                    6天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day7">-->
<!--                    7天总-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="day7now">
                    7天前
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="sunstocks">-->
<!--                    成员数-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 70px;" data-sort="sunstocksup">-->
<!--                    上涨数-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 60px;" data-sort="sunstocksupratio">-->
<!--                    上涨率-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 60px;" data-sort="sunstockslimit">
                    涨停数
                    <i class="fa fa-sort sort-icon"></i>
                </th>
<!--                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 60px;" data-sort="sunstockslimitratio">-->
<!--                    涨停率-->
<!--                    <i class="fa fa-sort sort-icon"></i>-->
<!--                </th>-->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 50px;"  data-sort="rankPosition">新 <i class="fa fa-sort sort-icon"></i></th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 50px;"  data-sort="oldRankPosition">上次 <i class="fa fa-sort sort-icon"></i></th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 50px;"  data-sort="rankChange">热涨 <i class="fa fa-sort sort-icon"></i></th>
                <!-- 趋势列添加排序功能 -->
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" style="width: 60px;" data-sort="trend">
                    趋势
                    <i class="fa fa-sort sort-icon"></i>
                </th>
            </tr>
            </thead>
            <tbody id="summaryTableBody" class="bg-white divide-y divide-gray-200">
            <!-- 表格内容将通过JavaScript动态填充 -->
            <tr class="text-center">
                <td colspan="26" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                        <p>正在加载数据...</p>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
        <!-- 添加表格统计信息区域 -->
        <div class="table-stats flex justify-between items-center">
            <div>
                显示 <span id="currentDisplayCount">0</span> 条，共 <span id="totalRecordCount">0</span> 条记录
            </div>
            <div>
                <i class="fa fa-info-circle mr-1"></i>
                <span id="filterStatus">未应用过滤</span>
            </div>
        </div>
    </div>

    <div id="emptyState" class="hidden text-center py-12">
        <i class="fa fa-info-circle text-4xl text-gray-400 mb-4"></i>
        <h3 class="text-xl font-medium text-gray-900 mb-2">暂无数据</h3>
        <p class="text-gray-500 max-w-md mx-auto">没有找到符合条件的概念数据，请确保数据库中有相关记录。</p>
    </div>
</div>

<div class="bg-white rounded-xl p-6 table-shadow hover-scale">
    <h2 class="text-xl font-semibold text-neutral-dark mb-6">数据说明</h2>
    <div class="grid md:grid-cols-2 gap-6">
        <div class="bg-blue-50 p-4 rounded-lg">
            <h3 class="font-medium text-primary mb-2 flex items-center">
                <i class="fa fa-lightbulb-o mr-2"></i>数据含义
            </h3>
            <ul class="list-disc list-inside text-gray-700 space-y-1">
                <li>各时间段数据为对应天数内的资金流向总和</li>
                <li>资金流向单位为元，保留两位小数</li>
                <li>数据按概念代码进行分组统计</li>
                <li>点击列标题可进行排序</li>
            </ul>
        </div>
        <div class="bg-green-50 p-4 rounded-lg">
            <h3 class="font-medium text-green-700 mb-2 flex items-center">
                <i class="fa fa-bar-chart mr-2"></i>数据分析
            </h3>
            <ul class="list-disc list-inside text-gray-700 space-y-1">
                <li>对比不同时间段数据，可分析资金流向趋势</li>
                <li>红色箭头表示资金流入减少趋势</li>
                <li>绿色箭头表示资金流入增加趋势</li>
                <li>支持按各天数列进行升序/降序排序</li>
            </ul>
        </div>
    </div>
</div>
</div>

<footer class="bg-neutral-dark text-white py-8 mt-12">
    <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="mb-4 md:mb-0">
                <h3 class="text-xl font-semibold mb-2">概念资金流向分析系统</h3>
                <p class="text-gray-400 text-sm">提供专业的股票概念数据分析服务</p>
            </div>
            <div class="flex space-x-6">
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-question-circle"></i> 帮助中心
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-file-text-o"></i> 使用文档
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-envelope-o"></i> 联系我们
                </a>
            </div>
        </div>
        <div class="border-t border-gray-700 mt-6 pt-6 text-center text-gray-400 text-sm">
            © 2025 概念资金流向分析系统. 保留所有权利.
        </div>
    </div>
</footer>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let currentData = [];
    let currentSortField = null;
    let currentSortDirection = 'asc';
    let allstocks = 0;//总的家数
    let stocksUP = 0;//上涨的家数
    let stocksDown = 0;//下跌的家数
    let stocksPin = 0;//平盘的家数
    let stocksLimit = 0;//涨停的家数
    let flowGainian = "";//关注的概念
    let isFiltered = false; // 新增：标记是否应用了过滤条件
    let createdAt = null; // 新增：存储最后更新时间

    $(document).ready(function() {
        // 为表格行绑定点击事件
        $('table').on('click', 'tr', function(e) {
            // 排除直接点击复选框的情况
            if($(e.target).is('input[type="checkbox"]')) return;

            // 获取当前行的复选框
            var $checkbox = $(this).find('.row-checkbox');

            // 切换选中状态
            $checkbox.prop('checked', !$checkbox.prop('checked'));

            // 可选：添加行高亮样式
            $(this).toggleClass('active', $checkbox.prop('checked'));
        });
    });

    document.addEventListener('DOMContentLoaded', function() {
        fetchData();

        // 合并后的查询/刷新按钮事件
        document.getElementById('searchBtn').addEventListener('click', performSearch);

        // 1. nameSearch实时变化时过滤现有数据
        document.getElementById('nameSearch').addEventListener('input', function() {
            filterExistingData();
        });

        // 2. startDate变化时调用接口获取新数据
        document.getElementById('startDate').addEventListener('change', function() {
            performSearch();
        });

        // 添加排序事件监听器
        document.querySelectorAll('.sortable-header').forEach(header => {
            header.addEventListener('click', function() {
                const sortField = this.getAttribute('data-sort');
                handleSort(sortField);
            });
        });

        // 设置默认日期为当天
        const today = new Date();
        document.getElementById('startDate').valueAsDate = today;

        // 全选复选框事件
        document.getElementById('select-all').addEventListener('click', setupCheckboxHandler);

        // 添加所有过滤条件的事件监听
        document.getElementById('trendFilter').addEventListener('input', filterExistingData);
        document.getElementById('memberCountFilter').addEventListener('change', filterExistingData);
        document.getElementById('changePercentFilter').addEventListener('change', filterExistingData);
        document.getElementById('day1Filter').addEventListener('change', filterExistingData);
        document.getElementById('upRatioFilter').addEventListener('change', filterExistingData);
        document.getElementById('limitUpRatioFilter').addEventListener('change', filterExistingData);

    });

    // 新增：重置所有过滤条件的函数
    function resetAllFilters() {
        // 重置所有输入框和下拉选择器
        document.getElementById('nameSearch').value = '';
        document.getElementById('trendFilter').value = 'all';
        document.getElementById('memberCountFilter').value = '';
        document.getElementById('changePercentFilter').value = '';
        document.getElementById('day1Filter').value = '';
        document.getElementById('upRatioFilter').value = '';
        document.getElementById('limitUpRatioFilter').value = '';

        // 重置过滤状态标记
        isFiltered = false;
        updateFilterStatus();

        // 重置排序状态
        currentSortField = null;
        currentSortDirection = 'asc';
        document.querySelectorAll('.sort-icon').forEach(icon => {
            icon.className = 'fa fa-sort sort-icon';
        });

        // 重新加载数据
        filterExistingData();
    }

    // 修改filterExistingData函数以包含新的过滤条件
    function filterExistingData() {
        const tableBody = document.getElementById('summaryTableBody');
        let nameSearch = document.getElementById('nameSearch').value.trim().toLowerCase();
        if (nameSearch === "=") {
            nameSearch = flowGainian;
        }

        // 获取所有过滤条件
        const trendFilter = document.getElementById('trendFilter').value;
        const memberCountFilter = document.getElementById('memberCountFilter').value.trim();
        const changePercentFilter = document.getElementById('changePercentFilter').value.trim();
        const day1Filter = document.getElementById('day1Filter').value.trim();
        const upRatioFilter = document.getElementById('upRatioFilter').value.trim();
        const limitUpRatioFilter = document.getElementById('limitUpRatioFilter').value.trim();

        // 检查是否有任何过滤条件被应用
        isFiltered = nameSearch !== '' || trendFilter !== 'all' || memberCountFilter !== '' ||
            changePercentFilter !== '' || day1Filter !== '' ||
            upRatioFilter !== '' || limitUpRatioFilter !== '';

        // 更新过滤状态显示
        updateFilterStatus();

        // 从现有数据中过滤
        let filteredData = [...currentData];

        // 名称模糊过滤
        if (nameSearch) {
            const searchTerms = nameSearch.toLowerCase().split(',').map(term => term.trim());
            filteredData = filteredData.filter(item => {
                const gainianName = item.gainianName.toLowerCase();
                const gainianNamepy = item.gainianNamepy ? item.gainianNamepy.toLowerCase() : '';
                const gaiFlag = gainianName.includes(nameSearch.toLowerCase()) ||
                    searchTerms.some(term => term && gainianName.includes(term));

                // const gaiFlag = gainianName === nameSearch.toLowerCase() ||
                //     searchTerms.some(term => gainianName === term);

                const gaiPyFlag = gainianNamepy.includes(nameSearch.toLowerCase()) ||
                    searchTerms.some(term => term && gainianNamepy.includes(term));
                return gaiFlag || gaiPyFlag;
            });
        }

        // 趋势过滤
        if (trendFilter && trendFilter !== 'all') {
            filteredData = filteredData.filter(item => {
                // 计算趋势文本，与显示的文本保持一致
                const day1 = Number(item.day1 || 0) / 10000 / 10000;
                const day2 = Number(item.day2now || 0) / 10000 / 10000;
                const day3 = Number(item.day3now || 0) / 10000 / 10000;

                let trendText;
                if (day1 > day2 && day2 > day3) {
                    trendText = '上升';
                } else if (day1 < day2 && day2 < day3) {
                    trendText = '下降';
                } else {
                    trendText = day1 > 0 ? '反转' : '平稳';
                }

                return trendText === trendFilter;
            });
        }

        // 成员数过滤
        if (memberCountFilter) {
            filteredData = filterByRange(filteredData, 'sunstocks', memberCountFilter);
        }

        // 涨幅过滤
        if (changePercentFilter) {
            filteredData = filterByRange(filteredData, 'changePercent', changePercentFilter, true);
        }

        // 1天资金过滤
        if (day1Filter) {
            // 1天资金需要先转换为亿元
            filteredData = filteredData.filter(item => {
                const value = Number(item.day1 || 0) / 10000 / 10000;
                return isInRange(value, day1Filter);
            });
        }

        // 上涨率过滤
        if (upRatioFilter) {
            filteredData = filteredData.filter(item => {
                const value = Number(item.rankPosition || 0);
                return isInRange(value, upRatioFilter);
            });
        }

        // 涨停率过滤
        if (limitUpRatioFilter) {
            filteredData = filterByRange(filteredData, 'sunstockslimitratio', limitUpRatioFilter, true);
        }

        // 更新记录数统计
        updateRecordCount(filteredData.length, currentData.length);

        // 处理过滤结果
        if (filteredData.length === 0) {
            tableBody.innerHTML = `
            <tr class="text-center">
                <td colspan="26" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-search text-3xl mb-3 text-gray-400"></i>
                        <p>没有找到匹配的数据</p>
                    </div>
                </td>
            </tr>
        `;
            return;
        }

        // 应用排序并渲染
        if (currentSortField) {
            const sortedData = sortData([...filteredData], currentSortField, currentSortDirection);
            renderTableData(sortedData);
        } else {
            renderTableData(filteredData);
        }
    }

    // 新增：更新过滤状态显示
    function updateFilterStatus() {
        const filterStatusEl = document.getElementById('filterStatus');
        if (isFiltered) {
            filterStatusEl.innerHTML = '<i class="fa fa-filter text-primary mr-1"></i>已应用过滤条件';
            filterStatusEl.className = 'text-primary';
        } else {
            filterStatusEl.textContent = '未应用过滤';
            filterStatusEl.className = '';
        }
    }

    // 新增：更新记录数统计
    function updateRecordCount(displayCount, totalCount) {
        document.getElementById('currentDisplayCount').textContent = displayCount;
        document.getElementById('totalRecordCount').textContent = totalCount;
    }

    // 通用范围过滤函数
    function filterByRange(data, field, rangeStr, isPercentage = false) {
        return data.filter(item => {
            let value;

            // 处理百分比数据（如"0.01%"）
            if (isPercentage) {
                // 从字符串中提取数值部分并转换为浮点数
                if (typeof item[field] === 'string') {
                    // 移除百分号并转换为浮点数
                    value = parseFloat(item[field].replace('%', ''));
                } else {
                    // 如果是数字类型，直接使用（可能已经是百分比的数值表示，如5表示5%）
                    value = Number(item[field] || 0);
                }
            } else {
                value = Number(item[field] || 0);
            }

            return isInRange(value, rangeStr);
        });
    }

    // 判断值是否在范围内
    function isInRange(value, rangeStr) {
        let min, max;

        // 处理"以上"的情况
        if (rangeStr.endsWith('+')) {
            min = parseFloat(rangeStr.replace('+', ''));
            max = Infinity;
            return value >= min;
        }

        // 处理"以下"的情况
        if (rangeStr.endsWith('-')) {
            max = parseFloat(rangeStr.replace('-', ''));
            min = -Infinity;
            return value <= max;
        }

        // 处理普通范围
        const [minStr, maxStr] = rangeStr.split('-');
        min = parseFloat(minStr);
        max = parseFloat(maxStr);

        // 处理负范围（如-5--3）
        if (minStr.startsWith('-') && maxStr.startsWith('-') && min < max) {
            [min, max] = [max, min]; // 交换位置使min < max
        }

        return value >= min && value <= max;
    }

    // 全选/取消全选功能实现
    function setupCheckboxHandler() {
        // 获取全选复选框元素
        const selectAllCheckbox = document.getElementById('select-all');

        // 获取所有行复选框
        const rowCheckboxes = document.querySelectorAll('input[name="select-stockCode"]');

        // 全选复选框变更事件
        selectAllCheckbox.addEventListener('change', function() {
            // 将所有行复选框的状态设置为与全选复选框一致
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });

        // 监听行复选框的变化，更新全选框状态
        rowCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                // 检查所有行复选框是否都被选中
                const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
            });
        });
    }


    // 执行查询（调用接口，用于startDate变化或点击查询按钮时）
    function performSearch() {
        // 重置所有过滤条件
        document.getElementById('trendFilter').value = 'all';
        document.getElementById('memberCountFilter').value = '';
        document.getElementById('changePercentFilter').value = '';
        document.getElementById('day1Filter').value = '';
        document.getElementById('upRatioFilter').value = '';
        document.getElementById('limitUpRatioFilter').value = '';

        // 重置过滤状态
        isFiltered = false;
        updateFilterStatus();

        const tableBody = document.getElementById('summaryTableBody');
        const nameSearch = document.getElementById('nameSearch').value.trim().toLowerCase();
        const startDate = document.getElementById('startDate').value;

        // 显示加载状态
        tableBody.innerHTML = `
            <tr class="text-center">
                <td colspan="26" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                        <p>正在查询数据...</p>
                    </div>
                </td>
            </tr>
        `;

        // 构建查询参数
        const params = new URLSearchParams();
        if (nameSearch) params.append('nameSearch', nameSearch);
        if (startDate) params.append('startDate', startDate);

        // 从URL获取code参数
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        if (code) params.append('code', code);

        // 调用接口获取新数据
        fetch(`/gainian/summarycodeData?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                currentData = data.result; // 更新全局数据

                allstocks = data.allstocks ;
                createdAt = data.result.createdAt ;
                stocksUP =data.stocksUP;
                stocksDown = data.stocksDown;
                stocksPin = data.stocksPin;
                stocksLimit = data.stocksLimit;
                flowGainian = data.flowGainian;

                // 新增：更新数据时间
                updateLastUpdateTime();

                // 更新统计数据显示
                updateStats();
                // 更新记录数统计
                updateRecordCount(data.result.length, data.result.length);

                if (data.result.length === 0) {
                    tableBody.innerHTML = `
                        <tr class="text-center">
                            <td colspan="26" class="px-6 py-12 text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-search text-3xl mb-3 text-gray-400"></i>
                                    <p>没有找到匹配的数据</p>
                                </div>
                            </td>
                        </tr>
                    `;
                    return;
                }

                // 应用排序并渲染
                if (currentSortField) {
                    sortAndRenderData();
                } else {
                    renderTableData(data.result);
                }
                filterExistingData();
            })
            .catch(error => {
                console.error('查询失败:', error);
                tableBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="26" class="px-6 py-12 text-red-500">
                            <div class="flex flex-col items-center">
                                <i class="fa fa-exclamation-triangle text-3xl mb-3"></i>
                                <p>加载数据失败，请稍后重试</p>
                            </div>
                        </td>
                    </tr>
                `;
                // 错误状态下更新记录数
                updateRecordCount(0, 0);
            });
    }

    /**
     * 批量打开选中的股票页面（每个股票在新标签页打开）
     */
    function openSelectedGainianCodesJQ() {
        // 获取所有选中的股票代码
        let selectedCodes = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get();

        // 处理未选中的情况
        if (selectedCodes.length === 0) {
            alert('请先选择股票');
            return;
        }
        // 遍历选中的每个股票代码，单独打开新页面
        selectedCodes.forEach(code => {
            // 为每个代码构建单独的URL（避免参数过长，且符合单股票页面设计）
            const targetUrl = `/gainian/summarycode?code=${encodeURIComponent(code)}`;
            // 每个股票在新标签页打开
            window.open(targetUrl, '_blank');
        });
    }

    function addupdateFocusGainian() {
        var focusGainian = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');

        if (!focusGainian || focusGainian.trim() === '') {
            alert('没有选择代码');
            return;
        }

        focusGainian=(focusGainian ? focusGainian.split('\n').join(',') : '');
        $.ajax({
            url: '/sysinfo/appendBy',
            method: 'GET',
            data: {
                focusGainian: focusGainian
            },
            success: function (response) {
                alert('关注成功');
            },
            error: function (xhr, status, error) {
                console.error('概念查询失败:', error);
                $('#loadingIndicator').removeClass('active');
                reject(error);
            }
        });
    }

    function removeupdateFocusGainian() {
        var focusGainian = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');

        if (!focusGainian || focusGainian.trim() === '') {
            alert('没有选择代码');
            return;
        }

        focusGainian=(focusGainian ? focusGainian.split('\n').join(',') : '');
        $.ajax({
            url: '/sysinfo/removeBy',
            method: 'GET',
            data: {
                focusGainian: focusGainian
            },
            success: function (response) {
                alert('取消关注成功');
            },
            error: function (xhr, status, error) {
                console.error('概念查询失败:', error);
                $('#loadingIndicator').removeClass('active');
                reject(error);
            }
        });
    }

    // 更新统计数据显示
    function updateStats() {
        // 获取页面上的统计元素
        const totalEl = document.getElementById('totalCount');
        const upEl = document.getElementById('upCount');
        const downEl = document.getElementById('downCount');
        const pinEl = document.getElementById('pinCount');
        const limitUpEl = document.getElementById('limitUpCount');
        const flowGainianEL = document.getElementById('flowGainian');

        // 更新元素内容（如果数据存在则显示，否则显示"-"）
        totalEl.textContent = allstocks !== undefined ? allstocks : '-';
        upEl.textContent = stocksUP !== undefined ? stocksUP : '-';
        downEl.textContent = stocksDown !== undefined ? stocksDown : '-';
        pinEl.textContent = stocksPin !== undefined ? stocksPin : '-';
        limitUpEl.textContent = stocksLimit !== undefined ? stocksLimit : '-';
        flowGainianEL.textContent = flowGainian !== undefined ? flowGainian : '-';
    }

    // 新增：更新最后更新时间
    function updateLastUpdateTime() {

        const formatTime = (createdAt) => {
            if (!createdAt) return '-';
            return new Date(createdAt).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        };
        document.getElementById('lastUpdateTime').textContent = `${formatTime(createdAt)}`;

    }

    // 处理排序
    function handleSort(sortField) {
        // 如果点击的是同一个字段，切换排序方向
        if (currentSortField === sortField) {
            currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            // 新字段默认降序（资金流向通常关注从大到小）
            currentSortField = sortField;
            // 文本字段默认升序
            currentSortDirection = ['gainianName', 'trend', 'gainianName'].includes(sortField) ? 'asc' : 'desc';
        }

        // 更新排序图标
        updateSortIcons(sortField, currentSortDirection);

        // 排序并重新渲染（使用当前过滤后的数据）
        const nameSearch = document.getElementById('nameSearch').value.trim().toLowerCase();
        let dataToSort = [...currentData];

        // 如果有搜索关键词，先过滤再排序
        if (nameSearch) {
            dataToSort = dataToSort.filter(item =>
                item.gainianName.toLowerCase().includes(nameSearch)
            );
        }

        filterExistingData();
    }

    // 通用排序函数
    function sortData(data, field, direction) {
        return [...data].sort((a, b) => {
            // 处理趋势排序
            if (field === 'trend') {
                // 先计算趋势值
                const trendA = getTrendValue(a);
                const trendB = getTrendValue(b);
                return direction === 'desc' ? trendB - trendA:trendA - trendB ;
            }

            if (field === 'rankChange') {
                // 先计算趋势值
                const trendA = calculateRankChange(a.rankPosition,a.oldRankPosition);
                const trendB = calculateRankChange(b.rankPosition,b.oldRankPosition);
                return direction === 'asc' ? trendA.value - trendB.value : trendB.value - trendA.value;
            }

            if (field === 'rankPosition') {
                const nameA = a[field] ? a[field] : 1000;
                const nameB = b[field] ? b[field] : 1000;
                return direction === 'asc' ? nameA - nameB : nameB - nameA;
            }

            // 处理概念名称排序（文本排序）
            if (field === 'gainianName') {
                const nameA = a[field] ? a[field].toLowerCase() : '';
                const nameB = b[field] ? b[field].toLowerCase() : '';
                return direction === 'asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
            }

            // 处理概念代码排序（文本排序）
            if (field === 'gainianCode') {
                const nameA = a[field] ? a[field].toLowerCase() : '';
                const nameB = b[field] ? b[field].toLowerCase() : '';
                return direction === 'asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA);
            }

            // 处理数值排序（天数数据）
            const aValue = parseFloat(a[field]) || 0;
            const bValue = parseFloat(b[field]) || 0;
            return direction === 'asc' ? aValue - bValue : bValue - aValue;
        });
    }

    // 获取趋势值（用于排序）
    function getTrendValue(item) {
        const day1 = Number(item.day1 || 0) / 10000 / 10000;
        const day2 = Number(item.day2now || 0) / 10000 / 10000;
        const day3 = Number(item.day3now || 0) / 10000 / 10000;

        // 上升=1，平稳=2，下降=3（便于排序）
        if (day1 > day2 && day2 > day3) {
            return 1; // 上升
        } else if (day1 < day2 && day2 < day3) {
            return 4; // 下降
        } else {
            if (day1>0){
                return 2; // 反转
            }else {
                return 3; // 平稳
            }
        }
    }

    // 更新排序图标
    function updateSortIcons(activeField, direction) {
        document.querySelectorAll('.sortable-header').forEach(header => {
            const icon = header.querySelector('.sort-icon');
            const field = header.getAttribute('data-sort');

            if (field === activeField) {
                icon.className = `fa ${direction === 'asc' ? 'fa-sort-up' : 'fa-sort-down'} sort-icon active`;
            } else {
                icon.className = 'fa fa-sort sort-icon';
            }
        });
    }

    // 排序并渲染数据（全局数据排序）
    function sortAndRenderData() {
        if (currentData.length === 0) return;

        const sortedData = sortData([...currentData], currentSortField, currentSortDirection);
        renderTableData(sortedData);
        // 更新记录数统计
        updateRecordCount(sortedData.length, currentData.length);
    }


    // 计算排名变化
    function calculateRankChange(current, old) {
        // 统一转换为数值类型，无法转换则视为无效值
        const currentRank = Number(current);
        const oldRank = Number(old);

        // 验证参数有效性（必须是有限数字且大于0，排名通常从1开始）
        if (isNaN(currentRank) || isNaN(oldRank) ||
            !isFinite(currentRank) || !isFinite(oldRank) ||
            currentRank <= 0 || oldRank <= 0) {
            return { class: 'text-gray-400', html: '-' };
        }
        const change = oldRank - currentRank;

        if (change < 0) {
            return {
                class: 'text-green-500 font-medium',
                value: change,
                html: `<i class="fa" aria-hidden="true"></i> ${Math.abs(change)}`
            };
        } else if (change > 0) {
            return {
                class: 'text-red-500 font-medium',
                value: change,
                html: `<i class="fa" aria-hidden="true"></i> ${change}`
            };
        } else {
            // 排名不变
            return {
                class: 'text-gray-500',
                value: change,
                html: `<i class="fa " aria-hidden="true"></i> 0`
            };
        }
    }

    // 渲染表格数据
    function renderTableData(data) {
        const tableBody = document.getElementById('summaryTableBody');
        tableBody.innerHTML = '';

        const formatTime = (createdAt) => {
            // 如果值为空，返回 '-'
            if (!createdAt) return '-';

            // 尝试创建日期对象
            const date = new Date(createdAt);

            // 检查是否为有效日期
            if (isNaN(date.getTime())) {
                // 不是有效时间格式，返回原始值
                return createdAt;
            }

            // 有效时间格式，返回格式化后的日期
            // return date.toLocaleString('zh-CN', {
            //     year: 'numeric',
            //     month: '2-digit',
            //     day: '2-digit'
            // });
            // 获取年、月、日
            const year = date.getFullYear();
            // 月份从0开始，需要加1，并且确保两位数字
            const month = String(date.getMonth() + 1).padStart(2, '0');
            // 确保日期是两位数字
            const day = String(date.getDate()).padStart(2, '0');

            // 拼接成YYYY-MM-DD格式
            return `${year}-${month}-${day}`;

        };

        data.forEach(item => {
            const row = document.createElement('tr');
            row.className = 'border-t border-gray-200 hover:bg-[#FFFF00] transition-colors';

            // 格式化数字（转换为亿元并保留两位小数）
            const formatNumber = (num) => {
                if (num === null || num === undefined) return '0.00';

                // 转换为亿元（除以10000万）
                const value = Number(num) / 10000 / 10000;
                const formattedValue = value.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });

                // 安全转义HTML特殊字符
                const escapedValue = formattedValue
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;');

                // 根据数值正负设置颜色（正数红色，负数绿色）
                if (value > 0) {
                    return `<span class="text-red-500">${escapedValue}</span>`;
                } else if (value < 0) {
                    return `<span class="text-green-500">${escapedValue}</span>`;
                }
                return escapedValue; // 0值默认颜色
            };

            const formatDouble = (num) => {
                if (num === null || num === undefined || num === 0) return '0.00';

                // 使用toFixed进行double格式化，保留2位小数
                const formattedValue = num.toFixed(2);

                // 安全转义HTML特殊字符
                const escapedValue = formattedValue
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;');

                // 根据数值正负设置颜色（正数红色，负数绿色）
                if (num > 0) {
                    return `<span class="text-red-500">${escapedValue}</span>`;
                } else if (num < 0) {
                    return `<span class="text-green-500">${escapedValue}</span>`;
                }
                return escapedValue; // 0值默认颜色
            };


            // 计算趋势
            const getTrendIcon = () => {
                const day1 = Number(item.day1 || 0) / 10000 / 10000;
                const day2 = Number(item.day2now || 0) / 10000 / 10000;
                const day3 = Number(item.day3now || 0) / 10000 / 10000;

                // 简单趋势判断：连续3天递增/递减
                if (day1 > day2 && day2 > day3) {
                    return '<i class="fa fa-arrow-up text-red-500 "></i> 上升';
                } else if (day1 < day2 && day2 < day3) {
                    return '<i class="fa fa-arrow-down text-green-500"></i> 下降';
                } else {
                    if (day1>0){
                        return '<i class="fa fa-arrow-up text-red-500 "></i> 反转'; // 反转
                    }else {
                        return '<i class="fa fa-minus text-gray-500"></i> 平稳';
                    }
                }
            };

            const rankChange = calculateRankChange(item.rankPosition, item.oldRankPosition);

            row.innerHTML = `
                    <td class="px-4 py-3 font-medium"><input type="checkbox" class="row-checkbox" name="select-stockCode" value="${item.gainianName || ''}" data-id="${item.gainianName || ''}"></td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 sm:text-right">${formatTime(item.createTime)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 sm:text-right">${formatNumbers(item.marketValue)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium ${formatNumberClass(item.changePercent)}">${item.changePercent}%</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
                               ${flowGainian && flowGainian.includes(item.gainianName) ? 'background-color: #FFFF00;' : ''}">
                      ${item.gainianName}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">${formatNumber(item.day1)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day2now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day3now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day4now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day5now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day6now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" style="background-color: #DFD3B9;">${formatNumber(item.day7now)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium ${formatNumberClass(item.sunstockslimit)}">${item.sunstockslimit}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 ">${item.rankPosition}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 ">${item.oldRankPosition}</td>
                    <td class="px-4 py-3 ${rankChange.class}">${rankChange.html}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${getTrendIcon()}</td>
                `;
            tableBody.appendChild(row);

            // <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day2)}</td>

            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day3)}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day4)}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day5)}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day6)}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day7)}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${item.sunstocks != null ? item.sunstocks : '-'}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 text-red-500">${item.sunstocksup}</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 ${formatNumberClass(item.sunstocksupratio)}">${formatDouble(item.sunstocksupratio)}%</td>
            // <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 ${formatNumberClass(item.sunstockslimitratio)}">${formatDouble(item.sunstockslimitratio)}%</td>
        });
    }

    // 根据数字正负设置样式类
    function formatNumberClass(number) {
        if (!number) return '';
        const num = new Number(number);
        if (num > 0) return 'text-red-500';
        if (num < 0) return 'text-green-500';
        return '';
    }

    // 格式化数字显示，保留2位小数且不显示千位分隔符
    function formatNumbers(number) {
        if (number === null || number === undefined || isNaN(number)) return '0';

        // 处理科学计数法的情况
        let num = typeof number === 'string' && number.includes('E')
            ? new Number(number)
            : Number(number);
        return num.toLocaleString('zh-CN', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2, // 确保始终显示2位小数
            useGrouping: false // 禁用千位分隔符
        });
    }

    function getSelectedStockCodesJQ() {
        let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');
        copyToClipboard(selectCode);
    }

    function jumpToEastMoneySearch() {
        // 直接跳转到目标URL
        let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');
        if (!selectCode || selectCode.trim() === '') {
            alert("未选择内容");
        }else{
            window.open("https://so.eastmoney.com/Web/s?keyword=" + selectCode, "_blank");
        }
    }

    // 初始加载数据
    function fetchData() {
        const tableBody = document.getElementById('summaryTableBody');
        const emptyState = document.getElementById('emptyState');

        // 显示加载状态
        tableBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="26" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                            <p>正在加载数据...</p>
                        </div>
                    </td>
                </tr>
            `;
        emptyState.classList.add('hidden');

        // 初始加载当天数据
        const today = new Date();
        const startDate = today.toISOString().split('T')[0]; // 格式化为YYYY-MM-DD
        const params = new URLSearchParams({ startDate });

        // 从URL获取code参数
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        if (code) params.append('code', code);

        fetch(`/gainian/summarycodeData?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.result.length === 0) {
                    tableBody.innerHTML = '';
                    emptyState.classList.remove('hidden');
                    // 更新记录数统计
                    updateRecordCount(0, 0);
                    return;
                }
                emptyState.classList.add('hidden');
                currentData = data.result; // 保存到全局变量

                allstocks = data.allstocks;
                createdAt = data.createdAt;
                stocksUP = data.stocksUP;
                stocksDown = data.stocksDown;
                stocksPin = data.stocksPin;
                stocksLimit = data.stocksLimit;
                flowGainian = data.flowGainian;

                // 新增：更新数据时间
                updateLastUpdateTime();

                // 初始渲染（无排序）
                renderTableData(data.result);
                filterExistingData();
                updateStats();
                // 更新记录数统计
                updateRecordCount(data.result.length, data.result.length);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                tableBody.innerHTML = `
                        <tr class="text-center">
                            <td colspan="26" class="px-6 py-12 text-red-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-exclamation-triangle text-3xl mb-3"></i>
                                    <p>加载数据失败，请稍后重试</p>
                                </div>
                            </td>
                        </tr>
                    `;
                // 错误状态下更新记录数
                updateRecordCount(0, 0);
            });
    }

    // 添加复制功能
    function copyToClipboard(stockCodes) {
        // 阻止事件冒泡，避免触发父元素的点击事件
        event.stopPropagation();

        if (!stockCodes || stockCodes.trim() === '') {
            alert('没有概念可复制');
            return;
        }

        // 使用现代浏览器的剪贴板API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(stockCodes).then(() => {
                // 显示成功提示
                showCopySuccessToast(stockCodes.split(',').length);
            }).catch(err => {
                console.error('复制失败:', err);
                fallbackCopy(stockCodes);
            });
        } else {
            // 降级方案
            fallbackCopy(stockCodes);
        }
    }

    // 降级复制方案
    function fallbackCopy(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('copy');
            showCopySuccessToast(text.split(',').length);
        } catch (err) {
            console.error('降级复制也失败了:', err);
            alert('复制失败，请手动复制：' + text);
        } finally {
            document.body.removeChild(textArea);
        }
    }

    // 显示复制成功的提示
    function showCopySuccessToast(count) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                z-index: 9999;
                font-size: 12px;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 8px;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease;
            `;

        toast.innerHTML = `
                <i class="fa fa-check-circle" aria-hidden="true"></i>
                已复制 ${count} 个概念
            `;

        document.body.appendChild(toast);

        // 动画显示
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 3秒后自动隐藏
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (document.body.contains(toast)) {
                    document.body.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }
</script>
</body>
</html>